package leetcode.lud;

import java.util.HashMap;

public class MyCache {
    private HashMap<String,Node> keyNodeMap;
    private HashMap<Node,String> nodeKeyMap;
    private NodeDoubleLinkedList nodeList;
    private int capacity;

    public MyCache(int capacity){
        if (capacity <1){
            throw new RuntimeException("should be more than 0");
        }
        this.keyNodeMap = new HashMap<>();
        this.nodeKeyMap = new HashMap<>();
        this.nodeList = new NodeDoubleLinkedList();
        this.capacity = capacity;
    }

    public int get(String key){
        if (this.keyNodeMap.containsKey(key)){
            Node res = this.keyNodeMap.get(key);
            this.nodeList.moveNodeToTail(res);
            return res.value;
        }
        return 0;
    }
    public void set(String key,int value){
        if (this.keyNodeMap.containsKey(key)){
            Node node = this.keyNodeMap.get(key);
            node.value =value;
            this.nodeList.moveNodeToTail(node);
        } else {
            Node newNode = new Node(value);
            this.keyNodeMap.put(key,newNode);
            this.nodeKeyMap.put(newNode,key);
            this.nodeList.addNode(newNode);
            if (this.keyNodeMap.size() == this.capacity+1){
                this.removeMostUnusedCache();
            }
        }
    }

    public void removeMostUnusedCache(){
        Node removeNode = this.nodeList.removeHead();
        String removeKey = this.nodeKeyMap.get(removeNode);
        this.nodeKeyMap.remove(removeNode);
        this.keyNodeMap.remove(removeKey);
    }
}
